package club.jdiy.dev.helper;

import club.jdiy.core.AppContext;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.core.sql.Dao;
import club.jdiy.core.sql.Rs;
import club.jdiy.dev.meta.TreeUiMeta;
import club.jdiy.utils.StringUtils;
import lombok.Getter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class TreeHelper {
    @Getter
    public static class Node {
        private final String id;
        private final String parentId;
        private final String sortPath;

        public Node(String id, String parentId, String sortPath) {
            this.id = id;
            this.parentId = parentId;
            this.sortPath = sortPath;
        }
    }

    public Node getParent(String table, TreeUiMeta treeUiMeta, String _trParentId) {
        Dao dao = appContext.getDao();
        Rs p = "0".equals(_trParentId) || StringUtils.isEmpty(_trParentId)
                ? dao.create(table)
                : dao.rs(table, _trParentId);
        return p.isNew()
                ? null
                : new Node(p.id(), p.getString(treeUiMeta.getPathField()), p.getString(treeUiMeta.getPathField()));
    }

    //isNew参数必须传过来，而不取rs.isNew()方法取!!! 因为添加时，是预先save了一遍，直接方法取，会始终返回false
    public void updateTreeFields(Rs rs, TreeUiMeta treeUiMeta, String _trParentId, boolean isNew) {
        Node p = getParent(rs.getTable(), treeUiMeta, _trParentId);
        if (p == null && StringUtils.hasText(_trParentId)) throw new JDiyException("上级节点不存在！");
        String pathField = treeUiMeta.getPathField();
        if (p == null) {
            rs.set(treeUiMeta.getPidField(), treeUiMeta.getRootPid().getDataValue());
            rs.set(pathField, "." + rs.id() + ".");
        } else {
            rs.set(treeUiMeta.getPidField(), p.getId());
            rs.set(pathField, p.getSortPath() + rs.id() + ".");
        }
        if (!isNew) {
            //更新子孙级节点的path字段：
            String oldPath = appContext.getDao()
                    .rs(String.format("select %s as p from %s where %s='%s'", pathField, rs.getTable(), rs.getPrimaryKey(), rs.id()))
                    .getString("p");
            appContext.getDao().exec(String.format("UPDATE %s SET %s=CONCAT('%s', RIGHT(%s,LENGTH(%s)-%d)) WHERE %s LIKE '%s%%'",
                    rs.getTable(), pathField, rs.get(pathField), pathField, pathField, oldPath.length(), pathField, oldPath));
        }
    }


    @Resource
    private AppContext appContext;
}
